var express = require('express');
var router = express.Router();
var db = require("../model/db");
var crypto = require('crypto');
var product = require('../model/product')
/* GET users listing. */

router.post('/register'
  , function (req, res, next) {
    console.log(req.body);
    let hash = crypto.createHash("md5").update(req.body.password);
    req.body.password = hash.digest("hex");
    db.add("user", Object.keys(req.body), Object.values(req.body)).then(data => {
      if (data > 0) {
        res.json({ errCode: 0, errMsg: "注册成功！~" });
      } else {
        res.json({ errCode: 1, errMsg: "注册失败！~" });
      }
    })

  });

router.post('/check', (req, res, next) => {
  if (req.body.uname != '') {
    db.search('user', req.body).then(
      data => {
        console.log(data);
        if (data.length > 0) {
          res.json({ errCode: 1, errMsg: '用户名已注册' });
        } else {
          res.json({ errCode: 0, errMsg: "用户名可以注册" });
        }
      },
      err => {
        console.log(err);
      }
    )
  } else {
    res.json({ errCode: 2, errMsg: '用户名不能为空' })
  }
})

router.post('/load', (req, res, next) => {
  let hash = crypto.createHash("md5").update(req.body.password);
  req.body.password = hash.digest("hex");
  //连接数据库，验证用户登录信息
  db.search("user", req.body).then(data => {
    //返回数据不为空，表示用户登录成功
    if (data.length > 0) {
      //将用户信息保存到cookie，页面关闭之后cookie会丢失
      res.cookie("uname", data[0].username);
      res.cookie("uid", data[0].id);
      //登入状态
      db.update("user",{is_login:1},{uname:req.body.uname}).then(data=>{

      })
      res.json({ errCode: 0, errMsg: "登入成功", userInfo: data[0] });
    } else {
      res.json({ errCode: 1, errMsg: "登入失败", userInfo: {} });
    }
  }, error => {
    console.log(error);
  })
})

//退出用户
router.post('/exit',(req,res)=>{
  db.update('user',{is_login:0},{uname:req.body.uname}).then();
})

router.post("/proserach",(req,res)=>{
  product.search('product',{name:req.body.name}).then(data=>{
      if(data.length>0){
        res.json({errCode:0,products:data});
      }
  })
})

router.post('/getAll',(req,res)=>{
   product.getAll("product").then(data=>{
    if(data.length>0){
      res.json({errCode:0,allProduct:data});
    }
   })
})
module.exports = router;
